﻿using Longbow.Web.SignalR;
using Microsoft.AspNetCore.SignalR;
#if NETSTANDARD2_0
using Newtonsoft.Json.Serialization;
#endif
using System;
using System.Threading.Tasks;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// SignalR 异常过滤器扩展方法
    /// </summary>
    public static class SignalRExceptionFilterExtensions
    {
#if NETSTANDARD2_0
        /// <summary>
        /// AddJsonProtocal 方法 内部设置序列化规则 时间类型格式字符串为 "yyyy-MM-dd HH:mm:ss"
        /// </summary>
        /// <param name="builder">ISignalRServerBuilder 实例</param>
        /// <returns></returns>
        public static ISignalRServerBuilder AddJsonProtocalDefault(this ISignalRServerBuilder builder)
        {
            return builder.AddJsonProtocol(options =>
            {
                options.PayloadSerializerSettings.ContractResolver = new DefaultContractResolver();
                options.PayloadSerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });
        }
#endif

        /// <summary>
        /// SignalR Exception Filter 注入方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="services">IServiceCollection 实例</param>
        /// <param name="handler">异常处理回调函数</param>
        /// <returns></returns>
        public static IServiceCollection AddSignalRExceptionFilterHandler<T>(this IServiceCollection services, Func<IHubContext<T>, Exception, Task> handler)
            where T : Hub
        {
            if (handler == null) throw new ArgumentNullException(nameof(handler));
            services.AddSingleton<ISignalRExceptionFilterHandler<T>>(new SignalRExceptionFilterHandler<T>(handler));
            return services;
        }
    }
}
